//
//  Repository.m
//  Coupit
//
//  Created by Deepak Kumar on 3/4/13.
//  Copyright (c) 2013 Home. All rights reserved.
//

#import "Repository.h"
#import "Repository_ContextAccess.h"
#import "NSManagedObjectContext+SafeInsert.h"

#define kDBName @"SecretFolder.sqlite"

@implementation Repository
{
    NSManagedObjectModel *model;
    NSPersistentStoreCoordinator *coordinator;
}

@synthesize context;

+(Repository*)sharedRepository {
    static Repository* instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[Repository alloc] init];
    });
    return instance;
}

-(id)init {
    if (self = [super init]) {
        model = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:[NSBundle mainBundle]]];
        coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        NSURL* storeUrl = [NSURL fileURLWithPath:documentsFilePath(kDBName)];
        NSError *error = nil;
        if (![coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
            NSAssert(false, @"Failed to add persistent store to coordinator");
            return nil;
        }
        context = [[NSManagedObjectContext alloc] init];
        [context setPersistentStoreCoordinator:coordinator];
    }
    return self;
}

inline static NSString* filePathInDirectory(NSString* fileName, NSSearchPathDirectory directory) {
    NSArray* paths = NSSearchPathForDirectoriesInDomains(directory, NSUserDomainMask, YES);
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kDecoyPasswordEntered] == YES) {
        NSString *tPath= [[paths objectAtIndex:0] stringByAppendingFormat:@"/Decoyfolder"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:tPath])
        {
            NSError* error;
            if([[NSFileManager defaultManager] createDirectoryAtPath:tPath withIntermediateDirectories:NO attributes:nil error:&error])
            {
                /* folder is created */
            }
            else
            {
//                NSLog(@"[%@] ERROR: attempting to  create session directory", [self class]);
//                NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
            }
        }
        return [ tPath stringByAppendingPathComponent:fileName];
    }
	return [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
}

inline static NSString* documentsFilePath(NSString* fileName) {
	return filePathInDirectory(fileName, NSDocumentDirectory);
}


- (NSArray *) fetchAllDirectories:(NSError **)error
{
    NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Directory"];
    NSArray *tArray = [context executeFetchRequest:fetchRequest error:error];
    if ([[NSUserDefaults standardUserDefaults] boolForKey:kDecoyPasswordEntered] == YES) {
        if ([tArray count]) {
            NSPredicate *tPredicate = [NSPredicate predicateWithFormat:@"mDecoyFolder == YES"];
            [fetchRequest setPredicate:tPredicate];
            tArray = [context executeFetchRequest:fetchRequest error:error];
            return tArray;
        }
        
    }
    
        return tArray;    
}

//- (BOOL) isAllGroupsLoaded
//{
//    return [[self fetchAllGroups:nil] count] ? YES : NO;
//}
//
//- (BOOL) deleteGiftCards:(GiftCards *)pGiftCards error:(NSError**)error
//{
//    return [self deleteObject:pGiftCards error:error];
//}

// Private Method
-(BOOL)deleteObject:(NSManagedObject*)object error:(NSError**)error
{
    [context deleteObject:object];
    return [context save:error];
}


@end
